import { useEffect, useState } from 'react';
import { Button, Dropdown, MenuProps, message, Space, Table, Tag } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { DataType } from './table/table';
import { useDispatch, useSelector } from 'react-redux';
import { DownOutlined } from '@ant-design/icons';
import { initUser } from '../../action/userAction';
import goodsModel from '../../model/goodsModel';
import './index.css'

export default function List(props: any) {

  const dispatch = useDispatch();
  const userInfo = useSelector((state: any) => state.userInfo.info);
  const [goodsList, setGoodsList] = useState([])
  const [isConsumer, setIsConsumer] = useState(false)

  const initData = async () => {
    setGoodsList([]);
    const params: any = {};
    if (userInfo && userInfo.type === 'merchant') {
      params.merchants = userInfo.username;
    }
    await goodsModel.query(params).then((res) => {
      setGoodsList(res.data)
    })
  }

  useEffect(() => {             // 页面加载完成
    const existInfo: any = window.localStorage.getItem("userinfo");
    if (!Object.keys(userInfo).length && !existInfo) {  // 全局的没有  本地缓存的也没有
      props.history.push("/");
    } else {                 //   说明用户登录了
      const cloneExistInfo = JSON.parse(existInfo);
      dispatch(initUser(cloneExistInfo));//数据更新了
      const params: any = {};
      if (cloneExistInfo && cloneExistInfo.type === 'consumer') {
        setIsConsumer(true);
      }
      if (cloneExistInfo && cloneExistInfo.type === 'merchant') {
        params.merchants = cloneExistInfo.username;
      }
      goodsModel.query(params).then((res) => {
        setGoodsList(res.data)
      })
    }
  }, [])


  const gotodetail = (id?: string) => { // 跳转详情编辑页
    if (id) {
      props.history.push({
        pathname: '/detail',
        search: `?id=${id}`
      });
    } else {
      props.history.push('/detail')
    }
  }

  const detail = async (id: number) => {
    await goodsModel.delete(id).then((res) => {
      if (res.status === 200) {
        message.success('删除成功')
      } else {
        message.error('删除失败')
      }
    })
    initData();
  }

  const exit = () => {
    localStorage.removeItem("userinfo");
    props.history.push("/");
  }

  const items: MenuProps['items'] = [   // 下拉退出
    {
      key: '1',
      label: (
        <p
          onClick={() => {
            exit()
          }}
          className="exit">
          退出登录
        </p>
      ),
    }
  ];

  const columns: ColumnsType<DataType> = [
    {
      title: '药品代码',
      dataIndex: 'code',
      key: 'code',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '药品名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '商家',
      dataIndex: 'merchants',
      key: 'merchants',
    },
    {
      title: '类别',
      key: 'category',
      dataIndex: 'category',
      render: (_, { category }) => (
        <Tag>{category}</Tag>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record: any) => (
        <Space size="middle">
          <Button onClick={() => { gotodetail(record.id) }} disabled={isConsumer}>编辑</Button>
          <Button onClick={() => { detail(record.id) }} disabled={isConsumer}>删除</Button>
        </Space>
      ),
    },
  ];


  return (
    <div className="live">
      <div className='con'>
        <div className='user'>
          <Dropdown menu={{ items }}>
            <span className="ant-dropdown-link" onClick={e => e.preventDefault()}>
              <span style={{ color: 'blue' }}>
                {userInfo.username} &nbsp;&nbsp;&nbsp;
              </span>
              <Tag>{userInfo.type}</Tag> <DownOutlined />
            </span>
          </Dropdown>
        </div>

        <div className='button'>
          <Button type="primary" onClick={() => { gotodetail() }} disabled={isConsumer}>
            新增
          </Button>
        </div>

        <Table
          rowKey={(record) => {
            return (record.id + Date.now())  //在这里加上一个时间戳就可以了
          }}
          onExpand={() => { return (<div>11</div>) }}
          columns={columns}
          dataSource={goodsList} />
      </div>
    </div>
  )
}






